package com.hzlh.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hzlh.common.util.MD5;
import com.hzlh.core.domain.UploadedFile;
import com.hzlh.core.service.UploadService;
import com.hzlh.core.utils.StringUtils;
import com.hzlh.domain.po.LoginAdmin;
import com.hzlh.domain.po.RolePo;
import com.hzlh.domain.po.UserRolesPo;
import com.hzlh.log.MethodLog;
import com.hzlh.service.LoginService;
import com.hzlh.service.RolePermService;
import com.hzlh.service.UserService;
import com.hzlh.service.AnchorResourceService;
import com.hzlh.shiro.ShiroUser;

@Controller
@RequestMapping("user")
public class UserController {
	
	private static final String uploadFirstSubDir = "user";
	@Autowired
	private UserService userService;
	@Autowired
	private RolePermService rolePermService;
	@Autowired
	@Qualifier("uploadFtpService")
	private UploadService uploadService;
	@Autowired
	private LoginService loginService;
	@Autowired
	private AnchorResourceService anchorResourceService;
 
	/**
	 * @Description: 获取用户分页列表数据
	 * @param pageIndex 当前页数
	 * @param pageSize 记录条数
	 * @return Map<String,Object>  
	 * @throws
	 * @author liu_wenfeng
	 * @date 2014年9月10日 下午3:34:26
	 */
	@MethodLog(key="USER.LIST")
	@RequestMapping("/page")
	@ResponseBody
	@RequiresPermissions("user:list")
	public Map<String,Object> page(int pageIndex,int pageSize){
		Subject subject = SecurityUtils.getSubject();
		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
		List<RolePo> rolesList= shiroUser.getUser().getRoles();
		int weight=rolesList.get(0).getWeight();
		return userService.userPage(weight,pageIndex, pageSize);
	}
	
	@MethodLog(key="LOGIN.LIST")
	@RequiresPermissions("loginUser:list")
	@RequestMapping("/login/page")
	@ResponseBody
	public Map<String,Object> loginPage(@RequestParam(value="startDate",required=false)String startDate,
			@RequestParam(value="endDate",required=false)String endDate,
			@RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="name",required=false)String name
			,int pageIndex,int pageSize){
		return userService.userLoginPage(startDate, endDate ,phone , name ,pageIndex, pageSize);
	}
	
	@RequestMapping("/active/page")
	@ResponseBody
	public Map<String,Object> activePage(@RequestParam(value="startDate",required=false)String startDate,
			@RequestParam(value="endDate",required=false)String endDate,
			@RequestParam(value="nameType",required=false)String nameType
			,int pageIndex,int pageSize){
		return userService.userActivePage(startDate, endDate ,nameType ,pageIndex, pageSize);
	}
	
	@MethodLog(key="REGISTER.LIST")
	@RequiresPermissions("registerUser:list")
	@RequestMapping("/register/page")
	@ResponseBody
	public Map<String,Object> registerPage(@RequestParam(value="startDate",required=false)String startDate,
			@RequestParam(value="endDate",required=false)String endDate,
			@RequestParam(value="phone",required=false)String phone,
			@RequestParam(value="name",required=false)String name,
			int pageIndex,int pageSize){
		return userService.userRegisterPage(startDate, endDate ,phone , name ,pageIndex, pageSize);
	}
	
	/**
	 * @Description: 新增用户初始化跳转
	 * @return String  
	 * @throws
	 * @author liu_wenfeng
	 * @date 2014年9月10日 下午3:32:44
	 */
	@RequiresPermissions("user:add")
	@RequestMapping("/add")
	public String add(Model model) {
		getRoles(model);
		return "user/add";  
	}
	
	@RequiresPermissions("user:edit")
	@RequestMapping("/edit")
	public String edit(Model model, Long id){
		LoginAdmin po = userService.getUser(id);
		StringBuffer sb = new StringBuffer();
		if(po.getRoles() != null && po.getRoles().size() >0){
			List<RolePo> rolePos= po.getRoles();
			for (int i = 0; i < rolePos.size(); i++) {
				sb.append(String.valueOf(rolePos.get(i).getId())).append(",");
			}
		}
		model.addAttribute("roleIds", sb.length() > 0 ? sb.substring(0, sb.length()-1) : "");
		model.addAttribute("user", po);
		getRoles(model);
		return "user/edit";
	}
	
	public void getRoles(Model model){
		List<RolePo> rolesList = new ArrayList<RolePo>();
		Subject subject = SecurityUtils.getSubject();
		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
		List<RolePo> roleList= shiroUser.getUser().getRoles();
		int weight=roleList.get(0).getWeight();
		List<RolePo> roles=rolePermService.roleList(new HashMap<String, Object>());
		for(int i=0;i<roles.size();i++){
			RolePo role = roles.get(i);
			if(role.getWeight()>=weight){
				rolesList.add(role);
			}
		}
		model.addAttribute("roles",rolesList);
	}
	
	@RequestMapping("/isUserExist")
	@ResponseBody
	public boolean isUserExist(String userId,Long id){
		return userService.isUserExist(userId,id) == 0;
	}
	
	/**
	 * @Description: 新增用户,并且批量绑定角色
	 * @param po
	 * @return String  
	 * @throws
	 * @author liu_wenfeng
	 * @date 2014年9月10日 下午3:30:53
	 */
	@MethodLog(key="USER.SAVE")
	@RequiresPermissions(value={"user:save","user:update"},logical=Logical.OR)
	@RequestMapping("/save")
	@ResponseBody
	public boolean save(LoginAdmin po,MultipartFile iconFile,
			HttpServletResponse response){
		boolean result = false;
		try {
			rolePermService.deleteUserRole(new Long[]{po.getId()});//首先，先清除用户数据
			//创建用户
			if(StringUtils.isNotBlank(po.getPwd())){
				po.setPwd(MD5.encode(po.getPwd()));//MD5 密码加密
			}
			if (iconFile != null && iconFile.getSize() > 0) {
				// 处理上传资料
				UploadedFile uploadedFile = uploadService.uploadFileToUploadDir(uploadFirstSubDir, iconFile);
				String url = uploadService.getUploadUrl() + uploadedFile.getReadUrl();
				po.setIcon(url);
			}
			
			if(po.getId() != null){
				userService.editUser(po);
			}else{
				userService.addUser(po);//创建用户
			}
			
			//创建用户角色
			if(po.getRoleIds() != null){
				List<UserRolesPo> urps = new ArrayList<UserRolesPo>(po.getRoleIds().length);
				for (String roleId : po.getRoleIds()) {
					UserRolesPo urp = new UserRolesPo();
					urp.setUserId(po.getId());
					urp.setRoleId(Long.valueOf(roleId));
					urps.add(urp);
				}
				rolePermService.batchAddUserRole(urps);//批量添加
			};
			
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-Type", "application/json"); // 处理图片上传代码
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * @Description: 删除用户（单个或批量）,并且删除关联表
	 * @param id
	 * @return boolean  
	 * @throws
	 * @author liu_wenfeng
	 * @date 2014年9月3日 下午4:16:33
	 */
	@MethodLog(key="USER.DELETE")
	@RequiresPermissions("user:delete")
	@RequestMapping("/delete")
	@ResponseBody
	public boolean delete(Long[] ids){
		//删除用户同时删除用户角色表
		rolePermService.deleteUserRole(ids);//清除关联表数据
//		anchorResourceService.deleteAResByUserId(ids);
		return userService.deleteUser(ids);
	}
	
	@RequestMapping("/topwd")
	public String topwd(Model model, Long id){
		model.addAttribute("id", id);
		return "user/repwd";
	}
	
	@RequestMapping("/updatePwd")
	@ResponseBody
	public boolean updatePwd(LoginAdmin po){
		boolean result = false;
		try {
			if(StringUtils.isNotBlank(po.getPwd())){
				po.setPwd(MD5.encode(po.getPwd()));//MD5 密码加密
			}
			userService.editUser(po);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping("/presenterList")
	@ResponseBody
	public List<LoginAdmin> getPresenterList(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", LoginAdmin.PRESENTER_CODE);
		return userService.getPresenterList(map);
	}
	
	@RequestMapping("/resourcePresenterList")
	@ResponseBody
	public List<LoginAdmin> getResourcePresenterList(Long resourceId ,Integer type){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("resourceId", resourceId);
		map.put("type", type);
		return userService.getResourcePresenterList(map);
	}
}